package org.paterczm.watermarker;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;

public class ImageResizer {
	
	public static Dimension getProportionalDimension(Dimension sourceDimension, Dimension targetDimension) {		

		float ratio = getRatio(sourceDimension, targetDimension);

		return new Dimension((int) (sourceDimension.width * ratio),
				(int) (sourceDimension.height * ratio));
	}
	
	public static float getRatio(Dimension sourceDimension, Dimension targetDimension) {
		float ratio_x = (targetDimension.width * 1f) / sourceDimension.width;
		float ratio_y = (targetDimension.height * 1f) / sourceDimension.height;

		return ratio_x < ratio_y ? ratio_x : ratio_y;
	}
	
	public static float getRatio(BufferedImage sourceImage, Dimension targetDimension) {
		return getRatio(new Dimension(sourceImage.getWidth(null), sourceImage.getHeight(null)), targetDimension);
	}

	public static BufferedImage resizeImage(BufferedImage image, float ratioX, float ratioY) {
		
		int newWidth = (int)(image.getWidth(null)*ratioX);
		int newHeight = (int)(image.getHeight(null)*ratioY);
		
		BufferedImage opImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);

		Graphics2D graphics2D = opImage.createGraphics();
		// graphics2D.drawImage(inputImage, 0, 0, inputImage.getWidth(null),
		// inputImage.getHeight(null), null);
		graphics2D.drawImage(image, 0, 0, newWidth,
				newHeight, null);

		return opImage;
	}
	
	public static BufferedImage resizeImage(BufferedImage image, float ratio) {
		return resizeImage(image, ratio, ratio);
	}
	
	public static BufferedImage scale(BufferedImage bi, float ratioX, float ratioY)
    {
        AffineTransform tx = new AffineTransform();
        tx.scale(ratioX, ratioY);
        AffineTransformOp op = new AffineTransformOp(tx,
                                         AffineTransformOp.TYPE_BICUBIC);
                       
        return op.filter(bi, null);
    }
	
	public static BufferedImage scale(BufferedImage bi, float ratio){
		return scale(bi, ratio, ratio);
	}

}
